package com.sias.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sias.oj.annotation.AuthCheck;
import com.sias.oj.common.BaseResponse;
import com.sias.oj.common.ErrorCode;
import com.sias.oj.common.ResultUtils;
import com.sias.oj.constant.UserConstant;
import com.sias.oj.exception.BusinessException;
import com.sias.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.sias.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.sias.oj.model.entity.QuestionSubmit;
import com.sias.oj.model.entity.User;
import com.sias.oj.model.vo.QuestionSubmitVO;
import com.sias.oj.service.QuestionSubmitService;
import com.sias.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 帖子点赞接口
 *
 * @author <a href="https://github.com/sogra">程序员sogra</a>
 */
@RestController
@RequestMapping("/question_submit")
@Slf4j
public class QuestionSubmitController {

  @Resource
  private QuestionSubmitService questionSubmitService;

  @Resource
  private UserService userService;

  /**
   * 提交题目
   *
   * @param questionSubmitAddRequest
   * @param request
   * @return 提交记录的id
   */
  @PostMapping("/")
  public BaseResponse<Long> doQuestionSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                             HttpServletRequest request) {
    if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    // 登录才能点赞
    final User loginUser = userService.getLoginUser(request);
    long result = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
    return ResultUtils.success(result);
  }

  /**
   * 分页获取题目提交列表（除了管理员外 普通用户只能看到非答案、提交代码等公开信息）
   *
   * @param questionSubmitQueryRequest
   * @param request
   * @return
   */
  @PostMapping("/list/page")
  public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                       HttpServletRequest request) {
    long current = questionSubmitQueryRequest.getCurrent();
    long size = questionSubmitQueryRequest.getPageSize();
    Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
            questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
    final User loginUser = userService.getLoginUser(request);
    // 返回脱敏信息
    return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, loginUser));
  }
}
